package com.ybkj.daijia.config;

import com.ybkj.daijia.Setting;
import com.ybkj.daijia.common.Result;
import com.ybkj.daijia.server.gasstation.PaymentsRecord;
import com.ybkj.daijia.server.gasstation.PaymentsRecord.RecordType;
import java.math.BigDecimal;
import java.util.Map;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.HttpServerErrorException;
import org.springframework.web.client.RestTemplate;

@Component
public class GasStationApi {

    /**
     * 根据油站id查询油价
     */
    public static final String FIND_PRICE_BY_STATION = "api/gasprice/findByGasStation";
    /**
     * 修改油价
     */
    public static final String SAVE_GAS_PRICE = "api/gasprice/saveGasPrice";
    /**
     * 修改油价直降
     */
    public static final String SAVE_GAS_PRICE_STRAIGHTDOWN = "api/gasprice/saveGasPriceStraightDown";
    /**
     * 修改油价排序
     */
    public static final String SAVE_GAS_PRICE_SORT = "api/gasprice/saveGasPriceSort";
    /**
     * 查询资金流水
     */
    public static final String QUERY_PAYMENTS_RECORD = "api/paymentsrecord/queryPaymentsRecord";
    /**
     * 保存资金流水
     */
    public static final String SAVE_PAYMENTS_RECORD = "api/paymentsrecord/savePaymentsRecord";
    /**
     * 查询客户最后一单
     */
    public static final String QUERY_LASTORDER_BY_PASSENGER = "api/order/queryLastByPassenger";
    /**
     * 支付订单
     */
    public static final String PAYMENT_ORDER = "api/order/paymentOrder";
    /**
     * 临时订单保存
     */
    public static final String PAYMENT_ORDER_TEMP = "api/ordertemp/paymentOrder";
    /**
     * 临时订单查询
     */
    public static final String FIND_ONE_ORDERTEMP = "api/ordertemp/queryById";
    /**
     * 临时订单支付
     */
    public static final String ORDERTEMP_TREAMENT = "api/ordertemp/treament";
    /**
     * 多条件查询加油站
     */
    public static final String QUERY_STATION_BYPARAMS = "api/gasstation/queryByParams";
    /**
     * 根据加油站id查询加油站评价信息.
     */
    public static final String QUERY_BY_GASSTATIONID = "api/review/queryByGSId";
    /**
     * 根据加油站id查询加油站.
     */
    public static final String CREATE = "api/gasstation/create";
    /**
     * 修改加油站.
     */
    public static final String UPDATE = "api/gasstation/update";
    /**
     * 修改登录账户密码.
     */
    public static final String UPDATE_PASSWORD = "api/gasstation/updatePassword";
    /**
     * 修改登录账号冻结.
     */
    public static final String UPDATE_FREEZE = "api/gasstation/updateFreeze";
    /**
     * 根据加油站id查询加油站.
     */
    public static final String QUERY_BY_ID = "api/gasstation/queryById";
    /**
     * 删除加油站.
     */
    public static final String DELETE = "api/gasstation/delete";
    /**
     * 根据加油站id查询加油站.
     */
    public static final String QUERY_STATION_ONE = "api/gasstation/queryGasStationOne";
    /**
     * 删除单条评价信息
     */
    public static final String DELETE_REVIEW = "api/review/delete";
    /**
     * 保存
     */
    public static final String CREATE_REVIEW = "api/review/review";
    /**
     * 根据加油站ID查询订单
     */
    public static final String QUERY_BY_GSID = "api/order/queryByGsId";
    /**
     * 根据订单ID查询订单
     */
    public static final String QUERY_BY_ORDERID = "api/order/queryById";
    /**
     * 根据订单ID确认加油
     */
    public static final String UPDATE_BY_ORDERID = "api/order/confirmRefuel";
    /**
     * 修改订单
     */
    public static final String UPDATE_BY_ORDER = "api/order/update";
    /**
     * 查询客户等级加油折扣
     */
    public static final String QUERY_BY_GRADEID = "api/discount/queryBypassengerGradeId";
    /**
     * 查询等级对应的加油站折扣
     */
    public static final String QUERY_ONE_GRADE = "api/discount/queryOne";
    /**
     * 修改客户等级加油折扣
     */
    public static final String UPDATE_BY_GRADEID = "api/discount/update";
    /**
     * 创建客户等级加油折扣
     */
    public static final String CREATE_BY_GRADEID = "api/discount/create";
    private static final Logger logger = LoggerFactory.getLogger(GasStationApi.class);
    @Value("${module.gasstation.url}")
    private String gasStationBaseURL;
    @Autowired
    private RestTemplate restTemplate;

    public String getGasStationBaseURL() {

        return gasStationBaseURL.endsWith("/") ? gasStationBaseURL : gasStationBaseURL + "/";
    }

    public void setGasStationBaseURL(String gasStationBaseURL) {
        this.gasStationBaseURL = gasStationBaseURL;
    }

    public RestTemplate getRestTemplate() {
        return restTemplate;
    }

    public void setRestTemplate(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }

    public String get(String apiurl, Map<String, String> kv, Setting setting) {
        kv.put("appKey", setting.getSecKey());

        String result = null;
        try {
            result = restTemplate.getForObject(apiurl, String.class, kv);
        } catch (HttpClientErrorException e) {
            e.printStackTrace();
            logger.error("HttpClientErrorException:code:{},status:{},body:{}", e.getStatusCode(),
                e.getStatusText(), e.getResponseBodyAsString());
            result = e.getResponseBodyAsString();
        } catch (HttpServerErrorException e) {
            e.printStackTrace();
            logger.error("HttpServerErrorException:{}", e.getResponseBodyAsString());
            result = e.getResponseBodyAsString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;

    }

    public String post(String apiurl, Map<String, String> kv, Setting setting) {

        kv.put("appKey", setting.getSecKey());

        String result = null;
        try {
            result = restTemplate.postForObject(apiurl, null, String.class, kv);
        } catch (HttpClientErrorException e) {
            logger.error("HttpClientErrorException:code:{},status:{},body:{}", e.getStatusCode(),
                e.getStatusText(), e.getResponseBodyAsString());
            result = e.getResponseBodyAsString();
        } catch (HttpServerErrorException e) {
            logger.error("HttpServerErrorException:{}", e.getResponseBodyAsString());
            result = e.getResponseBodyAsString();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return result;
    }

    public String postMultiValueMap(String apiurl, MultiValueMap<String, String> kv,
        Setting setting) {

        kv.add("appKey", setting.getSecKey());

        String result = null;
        try {
            result = restTemplate.postForObject(apiurl, kv, String.class);
        } catch (HttpClientErrorException e) {
            e.printStackTrace();
            logger.error("HttpClientErrorException:code:{},status:{},body:{}", e.getStatusCode(),
                e.getStatusText(), e.getResponseBodyAsString());
            result = e.getResponseBodyAsString();
        } catch (HttpServerErrorException e) {
            logger.error("HttpServerErrorException:{}", e.getResponseBodyAsString());
            result = e.getResponseBodyAsString();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return result;
    }

    public String put(String apiurl, Map<String, String> kv, Setting setting) {
        kv.put("appKey", setting.getSecKey());

        String result = null;
        try {
            restTemplate.put(apiurl, null, kv);
        } catch (HttpClientErrorException e) {
            e.printStackTrace();
            result = e.getResponseBodyAsString();
        } catch (HttpServerErrorException e) {
            e.printStackTrace();
            logger.error("HttpServerErrorException:{}", e.getResponseBodyAsString());
            result = e.getResponseBodyAsString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;

    }

    public Result<PaymentsRecord> savePaymentsRecord(Long gsId, BigDecimal money, String memo,
        String operating, RecordType recordType, Integer rcType, Setting setting) {
        Result<PaymentsRecord> result = new Result<PaymentsRecord>();
        result.setSuccess(false);

        StringBuilder sb = new StringBuilder();
        sb.append(getGasStationBaseURL()).append(GasStationApi.SAVE_PAYMENTS_RECORD);

        MultiValueMap<String, String> kv = new LinkedMultiValueMap<String, String>();
        kv.add("gsId", String.valueOf(gsId));
        kv.add("money", String.valueOf(money));
        if (StringUtils.isNotBlank(memo)) {
            kv.add("memo", memo);
        }
        kv.add("operating", operating);
        kv.add("recordType", recordType.toString());
        kv.add("rcType", String.valueOf(rcType));

        String resultStr = postMultiValueMap(sb.toString(), kv, setting);
        JSONObject jo = new JSONObject(resultStr);
        Integer code = jo.getInt("code");
        if (code == 0) {
            result.setSuccess(true);
        } else {
            result.setMessage(jo.getString("message"));
        }
        return result;
    }

    public String delete(String apiurl, Map<String, String> kv, Setting setting) {
        kv.put("appKey", setting.getSecKey());

        String result = null;

        try {
            restTemplate.delete(apiurl, kv);
        } catch (HttpClientErrorException e) {
            result = e.getResponseBodyAsString();
        }
        return result;
    }

}
